package it.crudity.web.beanutils;

import it.crudity.web.util.BeanPropertyMapFactory;

import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

/***
 * Aspect that intercepts controllers for converting returned beans to property
 * map
 */
@Aspect
public class PropertyMapBeanConverterAspect {

	/***
	 * 
	 * @see {@link BeanUtils#getProperty(Object, String)} for possible
	 *      exceptions thrown from {@link BeanPropertyMapFactory}
	 * 
	 */
	@Around("within(@org.springframework.stereotype.Controller *) && execution(@PropertyMapConvert public * *(..))")
	public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
		final Object realResult = pjp.proceed();
		MethodSignature msig = (MethodSignature) pjp.getSignature();
		/* Grab the annotation. */
		PropertyMapConvert annotation = msig.getMethod().getAnnotation(PropertyMapConvert.class);
		final String[] properties = annotation.value();

		Map<String, Object> propertyMap = BeanPropertyMapFactory.getBeanPropertyMap(properties, realResult);
		return propertyMap;

	}
}
